﻿using BMSPlatform.DeviceCommunication;
using BMSPlatform.View;
using BMSPlatform.ViewModel;
using DataManage;
using ServiceLayerManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BMSPlatform
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainViewModel VM => this.DataContext as MainViewModel;

        private ManualResetEvent recvBufferDataNumEvent = new ManualResetEvent(false);
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateRecvDataNum();
            nDeviceConnView.VM.Config = SerializeHelper.DeepCopy(GlobalData.PlatformConfig);
            nDeviceConnView.VM.CANStart = GlobalData.CANConnectState;

            nDeviceConnView.Visibility = Visibility.Visible;

            recvBufferDataNumEvent.Set();
        }

        /// <summary>
        /// CAN链接
        /// </summary>
        private void DeviecConnected_Click(object sender, RoutedEventArgs e)
        {
            nDeviceConnView.Visibility= Visibility.Visible;
            nAppUpgradeView.Visibility = Visibility.Collapsed;
        }
        /// <summary>
        /// BIN文件升级
        /// </summary>
        private void SystemUpgrade_Click(object sender, RoutedEventArgs e)
        {
            nDeviceConnView.Visibility = Visibility.Collapsed;
            nAppUpgradeView.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 接收缓冲区的数据量
        /// </summary>
        public async void UpdateRecvDataNum()
        {
            try
            {
                await Task.Factory.StartNew(() =>
                {
                    while (recvBufferDataNumEvent.WaitOne())
                    {
                        AppHelper.RunInUI(this, () =>
                        {
                            VM.RecvDataNum = DeviceConnected.RecvBufferNum;
                            AppHelper.Delay(100);
                        });
                    }
                });
            }
            catch
            {
                
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            recvBufferDataNumEvent.Reset();
        }
    }
}
